package com.yangxin.lesson.service.impl;

import com.mysql.jdbc.StringUtils;
import com.yangxin.lesson.entity.SysUser;
import com.yangxin.lesson.mapper.SysUserMapper;
import com.yangxin.lesson.service.UserService;
import com.yangxin.lesson.utils.PasswordUtils;
import com.yangxin.lesson.vo.request.RegisterRequestVo;
import com.yangxin.lesson.vo.request.UpdateUserRequestVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private SysUserMapper sysUserMapper;
//查询
    @Override
    public SysUser getUserInfo(String id) {
        return sysUserMapper.selectByPrimaryKey(id);
    }
//用户注册
    @Override
    public String register(RegisterRequestVo vo) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(vo,sysUser);//将Vo对象赋值给SysUser
        sysUser.setCreateTime(new Date());//用户创建时间
        sysUser.setId(UUID.randomUUID().toString());
        String salt = PasswordUtils.getSalt();//加密
        String encode= PasswordUtils.encode(vo.getPassword(),salt);//密文的密码
        sysUser.setPassword(encode);
        sysUser.setSalt(salt);
        int i =sysUserMapper.insertSelective(sysUser);
        if(i!=1){
            return  "对不起，您注册失败！可能因为您人不行！";
        }
        return "恭喜您，注册成功！";
    }
//用户更新
    //@Transactional(rollbackFor = Exception.class)//事务回滚
    @Override
    public String updateUserInfo(UpdateUserRequestVo vo) {
         SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(vo,sysUser);//将Vo对象赋值给SysUser
        if(StringUtils.isEmptyOrWhitespaceOnly(sysUser.getPassword())){
            sysUser.setPassword(null);
        }else{
            String salt = PasswordUtils.getSalt();
            String encode = PasswordUtils.encode(sysUser.getPassword(),salt);
            sysUser.setSalt(salt);
            sysUser.setPassword(encode);
        }
        sysUser.setUpdateTime(new Date());
        int i  = sysUserMapper.updateByPrimaryKeySelective(sysUser);
        if (i != 1){
            return  "更新失败！";
        }

      //  int k=1/0;
        return "更新成功！";
    }
//用户删除
    @Override
    public String deelteUserInfo(String id) {
        SysUser  sysUser = new SysUser();//创建一个用户
        sysUser.setUpdateTime(new Date());//时间
        sysUser.setDeleted(1);//状态1
        sysUser.setId(id);//根据Id删除
       int i  =  sysUserMapper.updateByPrimaryKeySelective(sysUser);
        if (i != 1) {
            return  "删除失败！";
        }
        return "删除成功！";
    }
}
